package com.cgc.shop.utils;

import java.io.File;
import java.util.UUID;

import org.apache.commons.io.FilenameUtils;
import org.aspectj.util.FileUtil;

import com.cgc.shop.model.ImageFile;

public class FileUploadUtil {
	private static final String IMAGE_PATH = "D:\\MyEclipseWorkspace\\.metadata\\.me_tcat\\webapps\\shopping\\images";
	
	/**
	 * 将上传文件保存到服务器images文件夹
	 * @param file
	 * @return 返回随机文件名，数据库保存的也是这个随机文件名
	 */
	public static String upload(ImageFile file) {
		String randomFileName = generateRandomFileName(file.getFileFileName());
		try {
			FileUtil.copyFile(file.getFile(), new File(IMAGE_PATH, randomFileName));
			return randomFileName;
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
	
	/**
	 * 生成随机随机文件名
	 * @param fileName
	 * @return 随机文件名
	 */
	public static String generateRandomFileName(String fileName) {
		String ext = FilenameUtils.getExtension(fileName);
		System.out.println("ext=" + ext);
		return UUID.randomUUID().toString() + "." + ext;
	}
}
